from django.contrib import admin
from .models import Category, Tag, Article, ArticleImage,Topic,Like,Collection
from django import forms
from django.core.exceptions import ValidationError
from django.contrib.admin import SimpleListFilter
from django.utils.html import format_html
class ArticleImageInlineFormSet(forms.models.BaseInlineFormSet):
    def clean(self):
        super().clean()
        article = self.instance
        if not article.pk:  # 新建文章时
            return

        # 检查是否有重复的图片
        valid_images = [
            form for form in self.forms
            if form.cleaned_data and not form.cleaned_data.get('DELETE', False)
        ]

        if article.article_type == 'single':
            if len(valid_images) > 1:
                raise ValidationError('单图类型最多只能上传一张图片')
            if valid_images:
                valid_images[0].cleaned_data['is_primary'] = True
        elif article.article_type == 'multi':
            if len(valid_images) < 2:  # 修改为统一验证
                raise ValidationError('多图类型至少需要上传2张图片')
class ArticleImageInline(admin.TabularInline):
    model = ArticleImage
    formset = ArticleImageInlineFormSet
    extra = 1
    fields = ('image', 'is_primary', 'order')
    readonly_fields = ('is_primary',)

    def get_readonly_fields(self, request, obj=None):
        if obj and obj.article_type == 'single':
            return ('is_primary',)
        return super().get_readonly_fields(request, obj)

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = '__all__'

    def clean(self):
        data = super().clean()
        article_type = data.get('article_type')
        image = data.get('image')
        # 新建对象时跳过多图数量检查（由内联表单后续处理）
        if not self.instance.pk and article_type == 'multi':
            return data

# 在Admin类中添加自定义过滤器


class StatusFilter(SimpleListFilter):
    title = '审核状态'
    parameter_name = 'status'

    def lookups(self, request, model_admin):
        return (
            ('pending', '待审核'),
            ('published', '已发布'),
            ('rejected', '已驳回'),
            ('draft', '草稿')
        )

    def queryset(self, request, queryset):
        if self.value():
            return queryset.filter(status=self.value())

# 在ArticleAdmin中更新list_filter

@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
    form = ArticleForm
    inlines = [ArticleImageInline]
    list_display = ('title', 'author', 'category', 'topics', 'article_type', 'status', 'is_commentable','is_top',
                    'like_count','views_count','comments_count','collect_count', 'publish_date')
    list_editable = ( 'is_top', 'status', 'is_commentable')
    list_filter = (StatusFilter, 'is_top', 'category', 'article_type')
    search_fields = ('title', 'content', 'author__username')
    prepopulated_fields = {'slug': ('title',)}
    autocomplete_fields = ('author', 'category')
    filter_horizontal = ('tags',)
    date_hierarchy = 'publish_date'
    ordering = ('-is_top', '-publish_date')
    actions = ['make_published', 'make_rejected', 'return_to_review', 'make_deleted']

    fieldsets = (
        ('作者信息', {
            'fields': ('author',)
        }),
        ('主要内容', {
            'fields': ('title', 'slug', 'content','article_type', 'image', 'category','topics', 'tags',)
        }),
        ('状态控制', {
            'fields': ('status','is_top', 'is_commentable','is_recommended')
        }),
        ('时间信息', {
            'fields': ('created_date','modified_date', 'publish_date')
        }),
    )

    def save_model(self, request, obj, form, change):
        # 显式调用save()来确保新建对象先保存
        obj.save()
        super().save_model(request, obj, form, change)
    def comment_status(self, obj):
        return obj.is_commentable
    comment_status.short_description = '评论状态'

    def make_published(self, request, queryset):
        queryset.update(status='published')
    make_published.short_description = "标记选定文章为已发布"

    def make_published(self, request, queryset):
        """批量发布文章"""
        updated = queryset.update(status='published')
        self.message_user(request, f"成功发布 {updated} 篇文章")
    make_published.short_description = "标记选定文章为已发布"
    def make_deleted(self, request, queryset):
        """批量删除文章"""
        updated = queryset.update(status='deleted')
        self.message_user(request, f"成功删除 {updated} 篇文章")
    make_deleted.short_description = "标记选定文章为已删除"
    def make_rejected(self, request, queryset):
        """批量驳回文章"""
        updated = queryset.update(status='rejected')
        self.message_user(request, f"已驳回 {updated} 篇文章")
    make_rejected.short_description = "标记选定文章为已驳回"
    def return_to_review(self, request, queryset):
        """批量退回待审"""
        updated = queryset.update(status='pending')
        self.message_user(request, f"已退回 {updated} 篇文章到待审状态")
    return_to_review.short_description = "标记选定文章为待审状态"
    def get_readonly_fields(self, request, obj=None):
        if obj:  # 编辑现有对象时
            return ('like_count', 'views_count', 'comments_count', 'collect_count')
        return ()

    def get_fields(self, request, obj=None):
        fields = super().get_fields(request, obj)
        if obj and obj.article_type == 'multi':
            return [f for f in fields if f != 'image']
        return fields



    class Media:
        js = ('article_type_control.js',)

@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
    list_display = ('name', 'cover_img','slug', 'parent','rank', 'created_date')
    list_filter = ('parent',)
    list_editable = ('rank','parent',)
    search_fields = ('name', 'slug',)
    prepopulated_fields = {'slug': ('name',)}
    autocomplete_fields = ('parent',)
    fieldsets = (
        ('分类信息', {
            'fields': ('name','slug', 'parent', 'description', 'cover')
        }),
        ('时间信息', {
            'fields': ('created_date','modified_date')
        }),
    )

    def get_queryset(self, request):
        return super().get_queryset(request).select_related('parent')
    #分类图片预览
    def cover_img(self, obj):
        if obj.cover:
            return format_html(
                '<img src="{}" style="max-height:50px;"/>',
                obj.cover.url
            )
        else:
            return format_html('<div style="color:gray">暂无图片</div>')  # 空状态提示
    cover_img.short_description = '分类图片'



@admin.register(Tag)
class TagAdmin(admin.ModelAdmin):
    list_display = ('name', 'color_code', 'created_date')
    search_fields = ('name',)
    list_display_links = ('name',)
    fields = ('name', 'color_code','description')

    def get_fields(self, request, obj=None):
        """创建时不强制显示颜色字段"""
        if obj:
            return super().get_fields(request, obj)
        return ('name',)
@admin.register(Topic)
class TopicAdmin(admin.ModelAdmin):
    list_display = ('name', 'created_date')
    search_fields = ('name',)
    list_display_links = ('name',)
    fields = ('name','description')

@admin.register(Like)
class LikeAdmin(admin.ModelAdmin):
    list_display = ('user', 'content_type', 'object_id', 'created_date')

@admin.register(Collection)
class CollectionAdmin(admin.ModelAdmin):
    list_display = ('user', 'content_type', 'object_id', 'created_date')